package top.xcxdl.rural.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j2;
import top.xcxdl.rural.entity.BackAuthGroup;
import top.xcxdl.rural.mapper.BackAuthGroupMapper;
import top.xcxdl.rural.service.IBackAuthGroupService;
import org.springframework.stereotype.Service;
import top.xcxdl.rural.utils.JWTUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Ding
 * @since 2022-01-27
 */
@Log4j2
@Service
public class BackAuthGroupServiceImpl extends ServiceImpl<BackAuthGroupMapper, BackAuthGroup> implements IBackAuthGroupService {

    @Resource
    private BackAuthGroupMapper mapper;

    @Override
    public List<BackAuthGroup> getRoles() {
        QueryWrapper<BackAuthGroup> wrapper = new QueryWrapper<>();
        return mapper.selectList(wrapper);
    }

    @Override
    public int getSuperAdminNum() {
        return mapper.getSuperAdminNum();
    }

    @Override
    public BackAuthGroup getGroupById(Integer aGroupId) {
        QueryWrapper<BackAuthGroup> wrapper = new QueryWrapper<>();
        wrapper.eq("g_id", aGroupId);
        return mapper.selectOne(wrapper);
    }

    @Override
    public PageInfo<BackAuthGroup> getList(Integer page_no, Integer page_size, String title) {
        PageHelper.startPage(page_no, page_size);
        QueryWrapper<BackAuthGroup> wrapper = new QueryWrapper<>();
        if (!"".equals(title)) {
            wrapper.like("title", title)
                    .or()
                    .like("`describe`", title)
                    .or()
                    .like("role",title);
        }
        return new PageInfo<>(mapper.selectList(wrapper));
    }

    @Override
    public int getByTitle(String title) {
        QueryWrapper<BackAuthGroup> wrapper = new QueryWrapper<>();
        wrapper.eq("title", title);
        return mapper.selectCount(wrapper);
    }

    @Override
    public int doEdit(BackAuthGroup bean) {
        if (bean.getGroupId() == null){
            //添加
            bean.setRole("ADMIN");
            return mapper.insert(bean);
        }else{
            //编辑
            QueryWrapper<BackAuthGroup> wrapper = new QueryWrapper<>();
            wrapper.eq("g_id",bean.getGroupId());
            return mapper.update(bean,wrapper) + 1;
        }
    }

    @Override
    public int doDeleteBy(List<Integer> ids) {
        QueryWrapper<BackAuthGroup> wrapper = new QueryWrapper<>();
        wrapper.in("g_id",ids);
        int ret = mapper.delete(wrapper);
        if(ret > 0 ){
            log.info("管理员{}（ID为{}）：删除了{}个角色，id为：{}", JWTUtils.getAuthorName(), JWTUtils.getAuthorId(),ids.size(),ids);
        }
        return ret;
    }

}
